package com.beiding.fastmock.plugin;

import com.beiding.dbrequest.common.Mapping;
import com.beiding.dbrequest.common.Request;
import com.beiding.dbrequest.common.SecondWorker;
import com.beiding.dbrequest.promise.Promise;
import com.beiding.fastmock.fram.call.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author 丁常磊
 * @date 2021/7/17 11:20
 */

@Component
@Mapping("/plugin-server")
@Slf4j
public class PluginController {

    private Map<String, Promise<Data>> runCallBack = new HashMap<>();

    @Mapping("/run")
    public Serializable run(Request request) {
        String id = (String) request.getBody();
        Promise<Data> func = runCallBack.remove(id);
        if (func != null) {
            func.doOk(new Data().set("status", 200).set("msg", "启动成功"));
        }
        return null;
    }

    public void registerRunCallBack(String id, String name, Promise<Data> promise, Integer ttl) {
        runCallBack.put(id, promise);
        SecondWorker.worker.schedule(() -> {
            if (runCallBack.remove(id) != null) {
                log.info("插件启动超时,可使用对应控制台查看具体日志 name={} ", name);
                promise.doError(new TimeoutException("插件启动超时"));
            }
        }, ttl, TimeUnit.SECONDS);
    }

}
